package com.zhuhao.design_mode.behavioral_pattern.observer_pattern;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * 天气数据为被观察者，数据被改变时通知天气数据布告版
 *
 * @Author zhuhao
 * @Date 2022/5/29 20:47
 * @desc
 */
@Data
public class WeatherData implements Subject {

    /**
     * 观察者列表
     */
    private List<Observer> observerList;
    /**
     * 温度
     */
    private float temperature;
    /**
     * 湿度
     */
    private float humidity;
    /**
     * 压强
     */
    private float pressure;

    /**
     * 类被创建时，创建一个观察者列表
     */
    public WeatherData() {
        observerList = new ArrayList<>();
    }

    /**
     * 当外界改变被观察者时，同步通知观察者
     *
     * @param temperature
     * @param humidity
     * @param pressure
     */
    public void setMeasurements(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        this.notifyObserver();
    }

    @Override
    public void registerObserver(Observer observer) {
        observerList.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        int i = observerList.indexOf(observer);
        if (i >= 0) {
            observerList.remove(observer);
        }
    }

    /**
     * 对观察者进行通知
     */
    @Override
    public void notifyObserver() {
        for (Observer o : this.observerList) {
            o.update(this.temperature, this.humidity, this.pressure);
        }
    }
}
